import { vw } from '@/common/dimensions';
import globalStyles from '@/common/styles/globalStyles';
import LazyImage from '@/components/LazyImage';
import NavHeader from '@/components/NavHeader';
import { categoryListAtom, activeCategoryIdAtom, categoryItemType, SceneItemType } from '@/store/home';
import { userImgParamsAtom, userInfoAtom } from '@/store/user';
import { beforeCreateTask } from '@/utils/createTask';
import { LinearGradient } from 'expo-linear-gradient';
import { useAtom } from 'jotai';
import React, { useEffect, useState } from 'react'
import { Image, StyleSheet, Text, View } from 'react-native'
import FooterButton from './FooterButton';
import Toast from 'react-native-toast-message';
import { createStylerServer } from '@/servers/app-servers';
import { useResultShow } from '@/hooks/useResultShow';
import { useUpdateUserInfo } from '@/hooks/useUpdateUserInfo';
import GlobalModal, { ModalPropsType } from '@/components/GlobalModal';
import { router } from 'expo-router';
import MonitorCode from '@/utils/MonitorCode';


export default function Styler(props: { id: number }) {
    let { id } = props;
    // 首页频道列表
    const [categoryList] = useAtom(categoryListAtom);
    // 当前选中的频道Id
    const [activeCategoryId] = useAtom(activeCategoryIdAtom);
    // 当前模板的封面
    const [coverImage, serCoverImage] = useState('')
    // 当前模板的标题
    const [navTitle, setNavTitle] = useState<string>("");
    // 用户信息
    const [userInfo] = useAtom(userInfoAtom)
    // 模板是否为收费模板
    const [chargeType, setChargeType] = useState('')
    // 收集 flowId
    const [flowId, setFlowId] = useState("")
    // 用户图片数据
    const [ImgParam] = useAtom(userImgParamsAtom)
    // 通用弹框是否显示
    const [showModal, setShowModal] = useState(false);
    // 自定义hook 获取 resultShow
    const { getResultShow } = useResultShow()
    // 自定义hook 更新userInfo
    const { updateUserInfo } = useUpdateUserInfo()

    // 关闭弹框
    const hideModal = () => {
        setShowModal(false)
    }

    // 去作品页
    const gotoWord = () => {
        hideModal()
        router.navigate('/(tabs)/work')
    }


    // 默认弹框数据
    const [modalProps, setModalProps] = useState<ModalPropsType>({
        title: "温馨提示",
        content: `提示内容`,
        cancelText: "取消",
        confirmText: "确定",
        onCancel: hideModal,
        onConfirm: hideModal,
        hideModal
    })


    useEffect(() => {
        const foundCategory = categoryList.find((item: categoryItemType) => item.id === activeCategoryId)?.sceneList.find((item: SceneItemType) => item.id === id) as SceneItemType;
        const { charge_type, json_content: { cn: { title }, cover_image, app_flow_id } } = foundCategory;
        setFlowId(app_flow_id)
        setNavTitle(title);
        setChargeType(charge_type)
        if (cover_image) serCoverImage(cover_image)
    }, [id, categoryList, activeCategoryId]);


    const onPressCreate = async () => {
        const res = beforeCreateTask(userInfo.is_pro, chargeType)
        if (!res) {
            Toast.show({
                type: "error",
                text1: "付费模板，请开通会员再尝试~"
            })
            return
        }
        let option = {
            flow_id: flowId,
            app_show_id: id,
            original_img_id: ImgParam.id
        }
        await createStyler(option)
    }

    const againCreate = async () => {
        let option = {
            flow_id: flowId,
            app_show_id: id,
            original_img_id: ImgParam.id,
            duplicate_check: 2,
        }
        await createStyler(option)
        await updateUserInfo()
    }

    const createStyler = async (data: any) => {
        const res = await createStylerServer(data)
        const { code } = res
        let modalProps;
        switch (code) {
            case 0:
                await getResultShow()
                await updateUserInfo()
                modalProps = MonitorCode.encounter(userInfo, hideModal ,gotoWord );
                break;
            case 1000:
                modalProps = MonitorCode.encounter1000(hideModal , againCreate);
                break;
            case 1001:
                modalProps = MonitorCode.encounter1001(hideModal);
                break;
        }
        if(modalProps){
            setModalProps(modalProps)
            setShowModal(true)
        }
    }


    return (
        <View>
            <LinearGradient
                colors={["#fdfaf2", "#fff"]}
                style={styles.container}
                start={{ x: 0, y: 1 }}
                end={{ x: 0, y: 0 }}
            >
                <NavHeader navTitle={navTitle} />
                <View
                    style={styles.coverImageContainer}
                >
                    {coverImage && (
                        <LazyImage
                            uri={coverImage}
                            style={styles.coverImage}
                            defaultSource={require("@/assets/common/perch.png")}
                        />
                    )}
                </View>
            </LinearGradient>
            <View style={{ backgroundColor: "#fff", paddingHorizontal: 4 * vw }}>
                <Text style={{ textAlign: "center", marginVertical: 4 * vw, fontWeight: 600, fontSize: 16 }}>选择你喜欢的图片</Text>
                <View style={[globalStyles.rowLine, globalStyles.aiCenter, globalStyles.jcSE, { marginBottom: 24 }]}>
                    <Image source={require("@/assets/createTask/tip-1.png")} style={styles.tipImage} />
                    <Image source={require("@/assets/createTask/tip-2.png")} style={styles.tipImage} />
                    <Image source={require("@/assets/createTask/tip-3.png")} style={styles.tipImage} />
                </View>
                <FooterButton onPressCreate={onPressCreate} />
            </View>
            <Toast />
            <GlobalModal
				visible={showModal}
				modalProps={modalProps}
			/>
        </View>
    )
}

const styles = StyleSheet.create({
    container: {
        paddingHorizontal: 4 * vw,
        paddingTop: 10 * vw,
    },
    coverImageContainer: {
        marginTop: 24
    },
    coverImage: {
        width: 92 * vw,
        height: 122 * vw,
        borderRadius: 24
    },
    tipImage: {
        width: 20 * vw,
        height: 20 * vw
    }
})